#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2018 crane <crane@crane-pc>
#
# Distributed under terms of the MIT license.
import scipy.stats as stats
from math import *


def confidence_interval(sample_mean, sample_sd, sample_size, confidence_level=.95):
    '''
    sd表示 stand deviation of sample
    默认是0.95概率的置信区间

    如果sample_size小于3, 需要用t表(因为此时不是正态分布型), 否则近似于正态分布(用正太分布z table)
    '''

    if sample_size < 30:
        interval_f = lambda conf_level : stats.t.interval(sample_size, conf_level)
    else:
        interval_f = lambda conf_level : stats.norm.interval(conf_level)

    sde = sample_sd / sqrt(sample_size) # standard deviation error: sample mean's standard deviation

    real_interval = [0] * 2

    z_interval = stats.norm.interval(confidence_level)   # 得出的是z-score区间(statis搜索z-table得出)

    # print(z_interval)
    real_interval[0] = sample_mean + sde * z_interval[0]
    real_interval[1] = sample_mean + sde * z_interval[1]
    return real_interval

def sample_mean_sd(n_0, n_1):
    ''' 01sample 求均值, 标准差 '''
    total_n = n_0 + n_1
    mean = n_1 / total_n

    variance_sum = n_0 * (mean-0) ** 2 + n_1 * (1-mean) ** 2
    variance = variance_sum / (total_n - 1)

    sd = sqrt(variance)
    # print(mean, sd)
    return mean, sd

def test():
    sample_mean, sample_sd = sample_mean_sd(250-142, 142)
    conf_interval = confidence_interval(sample_mean, sample_sd, 250, .99)
    print(conf_interval)


def main():
    print("start main")
    test()

if __name__ == "__main__":
    main()
